package com.ahdms.es.util;

import com.ahdms.es.gm.asn1.cipher.SM2Signature;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.x500.style.X500NameTokenizer;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.asn1.x509.CertificateList;

import java.math.BigInteger;

/**
 * @author qinxiang
 * @date 2021-04-09 13:48
 */
public abstract class IKICertUtils {

    public static boolean validateCrlSign(CertificateList crl, Certificate pkm) {
        try {
            //证书标识
            String identity = getPartFromDN(pkm.getSubject().toString(), "CN");

            //通过标识和公钥矩阵计算标识公钥（软实现）
            byte[] publicKey = IKIUtil.getPublicKeyFromPKM(pkm, identity);

            //根证书签名原文
            byte[] signData = crl.getTBSCertList().getEncoded();

            //根证书签名值
            byte[] sign = crl.getSignature().getOctets();

            //调用软件接口验证签名
           return SM2Utils.verifySign(publicKey, signData, AsnUtil.asn1ToByte(getSM2Signature(sign)));

        } catch (Exception e) {
            e.printStackTrace();
//            logger.error("证书验证标识私钥签名异常：", e);
        }

        return false;
    }


    /**
     * 验证证书标识私钥签名
     * @param cert
     * @param pkm
     * @return
     */
    public static boolean validateCertSign(Certificate cert, Certificate pkm) {
        boolean verifyResult = false;

        try {
            //证书标识
            String identity = getPartFromDN(cert.getSubject().toString(), "CN");

            //通过标识和公钥矩阵计算标识公钥（软实现）
            byte[] publicKey = IKIUtil.getPublicKeyFromPKM(pkm, identity);

            //根证书签名原文
            byte[] signData = cert.getTBSCertificate().getEncoded();

            //根证书签名值
            byte[] sign = cert.getSignature().getBytes();

            //调用软件接口验证签名
            verifyResult = SM2Utils.verifySign(publicKey, signData, AsnUtil.asn1ToByte(getSM2Signature(sign)));

        } catch (Exception e) {
            e.printStackTrace();
//            logger.error("证书验证标识私钥签名异常：", e);
        }

        return verifyResult;
    }

    private static String getPartFromDN(String dn, String dnpart) {
        String part = null;
        if ((dn != null) && (dnpart != null)) {
            String o;
            dnpart += "="; // we search for 'CN=' etc.
            X500NameTokenizer xt = new X500NameTokenizer(dn);
            while (xt.hasMoreTokens()) {
                o = xt.nextToken();
                // log.debug("checking: "+o.substring(0,dnpart.length()));
                if ((o.length() > dnpart.length()) && o.substring(0, dnpart.length()).equalsIgnoreCase(dnpart)) {
                    part = o.substring(dnpart.length());

                    break;
                }
            }
        }
        return part;
    }

    public static SM2Signature getSM2Signature(byte[] sign) {
        SM2Signature sm2Signature = null;
        if (null != sign) {

            byte[] bsR = ByteUtils.subBytes(sign, 0, 32); //取签名byte数组中R部分
            byte[] bsS = ByteUtils.subBytes(sign, 32, 32); //取签名byte数组中S部分

            ASN1Integer R = new ASN1Integer(new BigInteger(1, bsR));
            ASN1Integer S = new ASN1Integer(new BigInteger(1, bsS));
            sm2Signature = new SM2Signature(R, S);
        }
        return sm2Signature;
    }

}
